const config = Symbol('config')
const isCompleteURL = Symbol('isCompleteURL')
const requestBefore = Symbol('requestBefore')
const requestAfter = Symbol('requestAfter')
import store from '@/store'
import caches from '@/config/caches.js'


export const logout = () => {
	store.commit('SET_LOGOUT')
}

class MinRequest {
	[config] = {
		baseURL: '',
		header: {
			'content-type': 'application/x-www-form-urlencoded',
		},
		method: 'POST',
		responseType: 'text'
	}

	interceptors = {
		request: (func) => {
			if (func) {
				MinRequest[requestBefore] = func
			} else {
				MinRequest[requestBefore] = (request) => request
			}
		},
		response: (func) => {
			if (func) {
				MinRequest[requestAfter] = func
			} else {
				MinRequest[requestAfter] = (response) => response
			}
			// 注意：不要在这里调用 hideLoading()，应由业务处理程中控制
		}
	}

	static [requestBefore](config) {
		return config
	}

	static [requestAfter](response) {
		return response
	}

	static [isCompleteURL](url) {
		return /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
	}

	setConfig(func) {
		this[config] = func(this[config])
	}
	request(options = {}) {
		const url = options.url;
		options.baseURL = options.baseURL || this[config].baseURL
		options.dataType = options.dataType || this[config].dataType
		options.url = MinRequest[isCompleteURL](options.url) ? options.url : (options.baseURL + options.url)
		options.data = options.data
		options.header = this[config].header
		if (options.contentType) {
			options.header['content-type'] = options['contentType'];
		} else {
			options.header['content-type'] = 'application/json';
		}
		// TODO customer 客户端 走的 该拦截器
		// console.log(url, 'object :>>客户端接口/customer/', url.indexOf('/customer/'));
		// 业务员进入 客户端页面（列如 业务员可领取礼品 调用客户端接口 需要用客户端token） 接口以/customer/开头的是客户端接口 并且身份是业务员的用户salesman  直接使用客户端的token
		const authority = uni.getStorageSync(caches.AUTHORITY)
		if (options.url.indexOf('/customer/') !== -1) {
			const token = uni.getStorageSync(caches.CUSTOMER_TOKEN);
			// console.log(token)
			//  授权手机号 调用接口 根据返回 分析用户是 业务员 还是 客户  不需要token
			options.header['Authorization'] = token
		} else {
			// 正常客户端调用 接口 使用客户端的token
			const token = uni.getStorageSync(caches.ACCESS_TOKEN);
			options.header['Authorization'] = token
		}
		// 不需要 token的接口在 该数组里面加
		if (['/customer/open/applet/judgeBindingWithAppId'].includes(options.url)) options.header['Authorization'] = ''
		options.method = options.method || this[config].method

		options = {
			...options,
			...MinRequest[requestBefore](options)
		}
		let timer
		if (!options.hideLoading) {
			timer = setTimeout(() => {
				uni.showLoading({
					title: '加载中...'
				});
			}, 300)
		}

		return new Promise((resolve, reject) => {
			//接口请求返回固定某些code时，执行某些操作（如code等于1502时代表用户登录失效重新跳转登录）
			options.success = function (res) {
				clearTimeout(timer)
				if (timer) { // 只在显示了loading时才隐藏
					uni.hideLoading()
				}
				if (res.statusCode === 200) {
					if (res.data.code === 200 || res.data.code === 888) {
						resolve(MinRequest[requestAfter](res))
					} else {
						switch (res.data.code) {

							case 991:
							case 992:
							case 993:
							case 401:
								logout()
								uni.navigateTo({
									url: '/pages/user/phone/indexApp'
								})
								break;
						}
						if (res.data.code !== 401) {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						}
						reject(MinRequest[requestAfter](res))
					}
				} else {
					uni.showToast({
						title: res.data.error,
						icon: 'none'
					})
					reject(MinRequest[requestAfter](res))
				}
			}
			options.fail = function (err) {
				clearTimeout(timer)
				if (timer) { // 只在显示了loading时才隐藏
					uni.hideLoading()
				}
				reject(MinRequest[requestAfter](err) || '请求失败')
			}
			uni.request(options)
		})
	}

	get(url, data, options = {}) {
		options.url = url
		options.data = data
		options.method = 'GET'
		return this.request(options)
	}
	delete(url, data, options = {}) {
		options.url = url
		options.data = data
		options.method = 'DELETE'
		return this.request(options)
	}

	post(url, data, options = {}) {
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	}

	put(url, data, options = {}) {
		options.url = url
		options.data = data
		options.method = 'PUT'
		return this.request(options)
	}
}

MinRequest.install = function (Vue) {
	Vue.mixin({
		beforeCreate: function () {
			if (this.$options.minRequest) {
				Vue._minRequest = this.$options.minRequest
			}
		}
	})
	Object.defineProperty(Vue.prototype, '$minApi', {
		get: function () {
			return Vue._minRequest.apis
		}
	})
}

export default MinRequest